package ops.view.component;

import java.awt.Toolkit;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 * A {@link JTextField} that only accepts input within a limited range.
 * Default size is 10.
 * @author flavio
 */
public class LimitedSizeField extends JTextField {
	
	public LimitedSizeField() {
		this("");
	}
	
	public LimitedSizeField(Object obj) {
		this(obj, 10);
	}
	
	public LimitedSizeField(int size) {
		this("", size);
	}
	
	public LimitedSizeField(Object obj, int size) {
		this(new LimitedSizeDocument(size), obj.toString(), size);
	}
	
	protected LimitedSizeField(LimitedSizeDocument doc, Object obj, int size) {
		super(doc, obj.toString(), size);
	}
	
	protected static class LimitedSizeDocument extends PlainDocument {
	    private int limit;
	    
	    public LimitedSizeDocument(int limit) {
	        super();
	        this.limit = limit;
	    }

	    @Override
	    public void insertString(int offset, String str, AttributeSet attr)
	            throws BadLocationException {
	        if (str == null || str.equals(""))
	        	return;
	        
	        if ((getLength() + str.length()) <= limit) {
	            super.insertString(offset, str, attr);
	        } else {
	            Toolkit.getDefaultToolkit().beep();
	        }
	    }
	}
}
